<template>
  <div class="oss-provider-switch">
    <el-card class="provider-card">
      <template #header>
        <div class="card-header">
          <span>OSS 提供商配置</span>
        </div>
      </template>

      <el-form :model="config" label-width="120px">
        <el-form-item label="提供商">
          <el-select v-model="config.provider" @change="handleProviderChange">
            <el-option label="阿里云 OSS" :value="OssProvider.ALIYUN" />
            <el-option label="本地文件系统" :value="OssProvider.LOCAL" />
          </el-select>
        </el-form-item>

        <template v-if="config.provider === OssProvider.ALIYUN">
          <el-form-item label="Access Key ID">
            <el-input v-model="config.accessKeyId" placeholder="请输入 Access Key ID" />
          </el-form-item>
          <el-form-item label="Access Key Secret">
            <el-input v-model="config.accessKeySecret" type="password" placeholder="请输入 Access Key Secret" />
          </el-form-item>
          <el-form-item label="Bucket 名称">
            <el-input v-model="config.bucketName" placeholder="请输入 Bucket 名称" />
          </el-form-item>
          <el-form-item label="Endpoint">
            <el-input v-model="config.endpoint" placeholder="请输入 Endpoint" />
          </el-form-item>
        </template>

        <template v-if="config.provider === OssProvider.LOCAL">
          <el-form-item label="基础路径">
            <el-input v-model="config.basePath" placeholder="请输入本地存储基础路径" />
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSwitch" :loading="loading">
            切换提供商
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { OssProvider } from '../types/oss';
import { ossApi } from '../api/oss';

const config = ref({
  provider: OssProvider.LOCAL,
  accessKeyId: '',
  accessKeySecret: '',
  bucketName: '',
  endpoint: '',
  basePath: '/tmp/anysdk-oss'
});

const loading = ref(false);

const handleProviderChange = () => {
  // 切换提供商时重置相关配置
  if (config.value.provider === OssProvider.LOCAL) {
    config.value.accessKeyId = '';
    config.value.accessKeySecret = '';
    config.value.bucketName = '';
    config.value.endpoint = '';
  } else {
    config.value.basePath = '';
  }
};

const handleSwitch = async () => {
  try {
    loading.value = true;
    await ossApi.switchProvider(config.value);
    ElMessage.success('切换提供商成功');
  } catch (error) {
    ElMessage.error('切换提供商失败');
    console.error('切换提供商失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.oss-provider-switch {
  margin-bottom: 20px;
}

.provider-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>